package com.guigu.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.pojo.Orders;
import com.guigu.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guigu.pojo.*;
import com.guigu.service.CartService;
import com.guigu.service.OrderDetailsService;
import com.guigu.service.OrderPaymentService;
import com.guigu.service.OrdersService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @PostMapping("getAllOder")
    @ResponseBody
    public Page<Orders> getAllOder(@RequestBody HashMap<String, Object> map) {
        Page<Orders> allOrder = ordersService.getAllOrder(map);
        System.out.println(allOrder);
        return allOrder;
    }


    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private OrderPaymentService orderPaymentService;

    @Autowired
    private CartService cartService;

    @PostMapping("/exAdd")
    @ResponseBody
    public Orders exAdd(@RequestBody HashMap<String, Object> map) throws Exception {

        Object user = map.get("user");
        Object carts = map.get("carts");
        Object checkoutForm = map.get("checkoutForm");

        // 将 LinkedHashMap 转换为 Consumer 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Consumer consumer = objectMapper.convertValue(user, Consumer.class);
        List cartsList = objectMapper.convertValue(carts, ArrayList.class);
        HashMap checkoutFormMap = objectMapper.convertValue(checkoutForm, HashMap.class);

        // 生成订单
        Orders orders = new Orders();
        // 生成订单号
        long orderNoLong = getOrderNo();  // long 类型订单号
        String orderNoString = String.valueOf(orderNoLong);  // 转换为 String 类型存储在数据库
        orders.setOrderNumber(orderNoString);
        orders.setConsumerId(consumer.getConsumerId());
        orders.setMerchantId(Integer.parseInt(checkoutFormMap.get("merchantId").toString()));
        orders.setTotalPrice(Float.parseFloat(checkoutFormMap.get("subtotal").toString()));
        orders.setCreateDate(new Date());
        orders.setOnOff(1);
        orders.setPayMethod(checkoutFormMap.get("payment").toString());
        orders.setPayTag("K002-1");
        orders.setConveyTag("P001-1");
        orders.setStatus("C001-1");
        boolean save = ordersService.save(orders);
        System.out.println(orders);

        // 插入订单详情
        // 为每个购物车生成订单详情
        for(Object c : cartsList){
            Cart cart = objectMapper.convertValue(c, Cart.class);
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setProductId(cart.getProductId());
            orderDetails.setOrdersId(orders.getOrderId());
            orderDetails.setAmount(cart.getNum());
            orderDetails.setPrice(cart.getProduct().getPrice());
            orderDetails.setSubtotal(cart.getProduct().getPrice() * cart.getNum());
            boolean save1 = orderDetailsService.save(orderDetails);
            System.out.println(orderDetails);
            cartService.removeById(cart.getCartId());
        }
        // 插入订单支付
        OrderPayment orderPayment = new OrderPayment();
        orderPayment.setOrderId(orders.getOrderNumber());
        orderPayment.setPaymentMethod(orders.getPayMethod());
        orderPayment.setPaymentAmount(orders.getTotalPrice());
        orderPayment.setPaymentTime(new Date());
        orderPayment.setPaymentStatus("K002-1");
        orderPayment.setAlipayOrderOn("");
        boolean save1 = orderPaymentService.save(orderPayment);
        System.out.println(orderPayment);

        return orders;
    }


    // 生成订单号（long 类型）
    private static String date;
    private static long orderNum = 0L;

    public static synchronized long getOrderNo() {
        String str = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        if (date == null || !date.equals(str)) {
            date = str;
            orderNum = 0L;
        }
        orderNum++;
        long orderNO = Long.parseLong(date) * 10000;
        orderNO += orderNum;
        return orderNO;  // 返回 long 类型订单号
    }

    @PostMapping("/getOrderByMerchantIdOrConsumerId")
    @ResponseBody
    public Page<Orders> getOrderByMerchantId(@RequestBody HashMap<String, Object> map) throws Exception {
        Page<Orders> page = ordersService.getOrderByMerchantIdOrConsumerId(map);
        return page;
    }

    @GetMapping("/receivingByOrderId")
    @ResponseBody
    public Boolean receivingByOrderId(@RequestParam("orderId") Integer orderId){
        Orders orders = ordersService.getById(orderId);
        orders.setConveyTag("P001-3");
        boolean b = ordersService.updateById(orders);
        return b;
    }

    @GetMapping("/deliveryByOrderId")
    @ResponseBody
    public Boolean deliveryByOrderId(@RequestParam("orderId") Integer orderId){
        Orders orders = ordersService.getById(orderId);
        orders.setConveyTag("P001-4");
        boolean b = ordersService.updateById(orders);
        return b;
    }

    @GetMapping("/getMerchantOrderCountByMerchantId")
    @ResponseBody
    public Integer getMerchantOrderCountByMerchantId(Integer merchantId){
        Integer count = ordersService.getMerchantOrderCountByMerchantId(merchantId);
        return count;
    }

    @GetMapping("/cancelOrder")
    @ResponseBody
    public Boolean cancelOrder(@RequestParam("orderNumber") String orderNumber){
        Boolean b =ordersService.cancelOrder(orderNumber);
        return b;
    }

    @PostMapping("/getAllocateOrder")
    @ResponseBody
    public Page<Orders> getAllocateOrder(@RequestBody HashMap<String, Object> map){
        Page<Orders> allocateOrder = ordersService.getAllocateOrder(map);
        return allocateOrder;
    }
}

